package com.okq.action;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.okq.action.base.BaseActionSupport;
import com.okq.entity.Customer;
import com.okq.entity.Order;
import com.okq.entity.User;
import com.okq.entity.base.DataEntity;
import com.okq.service.ICustomerService;
import com.okq.service.ILogService;
import com.okq.service.IOrderProductService;
import com.okq.service.IOrderService;
import com.okq.service.IUserService;
import com.okq.util.BaseTool;
import com.okq.util.PublicClass;
import com.okq.util.TimeTool;
import com.okq.util.page.Page;
/**
 * 描述 : 工单列表 作者 : zjl 日期 : 2017/8/5 10:05
 */
public class OrderAction extends BaseActionSupport {
	private static final long serialVersionUID = 8978741529355704312L;

	/**
	 * 订单服务层接口
	 */
	@Autowired
	private IOrderService orderServiceImpl;

	/**
	 * 订单产品接口
	 */
	@Autowired
	private IOrderProductService orderProductServiceImpl;
	/**
	 * 客户接口
	 */
	@Autowired
	private ICustomerService customerServiceImpl;
	/**
	 * 用户接口
	 */
	@Autowired
	private IUserService userServiceImpl;
	/**
	 * 系统日志接口
	 */
	@Autowired
	private ILogService logServiceImpl;
	/**
	 * 日志
	 */
	private static final Logger logger = Logger.getLogger(JobAction.class);
	/**
	 * 分页开始条数
	 */
	private int iDisplayStart;

	/**
	 * 每页显示条数
	 */
	private int iDisplayLength;

	public int getiDisplayLength() {
		return iDisplayLength;
	}

	public void setiDisplayLength(int iDisplayLength) {
		this.iDisplayLength = iDisplayLength;
	}

	public Order getOrder() {
		return order;
	}

	public void setOrder(Order order) {
		this.order = order;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	private Order order;
	private String type;
	private String id;

	// getlist
	public String getOrderList() {

		PrintWriter out = null;
		try {
			out = this.getResponse().getWriter();
			User loginUser = (User) getSession().getAttribute("loginUser");
			if (loginUser != null) {
				if (iDisplayLength == 0) {
					iDisplayLength = -1;
				}
				int pageNum = (int) (Math.ceil(iDisplayStart / iDisplayLength)) + 1;
				/* 分页信息 */
				Page<Order> pageInfo = new Page<>(iDisplayLength);
				pageInfo.setPageNo(pageNum);
				pageInfo = orderServiceImpl.pageByOrder(pageInfo, order);
				int iTotalRecords = pageInfo.getTotalCount();
				int iTotalDisplayRecords = pageInfo.getTotalCount() < 0 ? 0 : pageInfo.getTotalCount();

				/* 得到结果 */
				List<Order> oList = pageInfo.getResult();

				/* 封装list */
				List<Map<String, Object>> orderMapList = new ArrayList<>();
				if (oList != null && !oList.isEmpty() && oList.size() > 0) {
					int i = (pageNum - 1) * iDisplayLength + 1;
					for (Order o : oList) {
						Map<String, Object> map = new HashMap<>();
						// 序号
						map.put("no", i);
						// 订单id
						map.put("id", o.getId());
						// 客户id查 客户名称，客户地址
						String customerId = StringUtils.defaultString(o.getCustomerId(), "");
						String customerName = "";
						String customerAddress = "";
						if (StringUtils.isNotBlank(customerId)) {
							Customer c = customerServiceImpl.getCustomerById(customerId);
							if (c != null) {// userServiceImpl
								customerName = StringUtils.defaultString(c.getName(), "");
								customerAddress = StringUtils.defaultString(c.getAddress(), "");
							}
						}
						// name address
						map.put("customerName", customerName);
						map.put("customerAddress", customerAddress);
						// 交付时间
						map.put("deliverTime", o.getDeliverTime());
						// 项目经理id 查询名称
						String chargeName = "";
						String chargeId = o.getChargeId();
						if (StringUtils.isNotBlank(chargeId)) {
							User u = userServiceImpl.getUserById(chargeId);
							if (u != null) {
								chargeName = StringUtils.defaultString(u.getUserName(), "");
							}
						}
						map.put("chargeName", chargeName);
						orderMapList.add(map);
						i++;
					}
				}
				Map<String, Object> jsonMap = new HashMap<>();
				jsonMap.put("iTotalRecords", iTotalRecords);
				jsonMap.put("iTotalDisplayRecords", iTotalDisplayRecords);
				jsonMap.put("aaData", orderMapList);
				String json = BaseTool.toJson(jsonMap);
				out.print(json);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return null;
	}

	/**
	 * 删除订单列表
	 * 
	 * @return
	 */
	public String deleteOrder() {
		PrintWriter out = null;
		try {
			out = this.getResponse().getWriter();
			User loginUser = (User) getSession().getAttribute("loginUser");
			if (loginUser != null && StringUtils.isNotBlank(id)) {
				Order o = orderServiceImpl.getOrderById(id);
				if (o != null) {
					o.setIsDelete(1);
					// 删除订单记录
					orderServiceImpl.updateOrder(o);

					out.print(0);
					// 添加系统日志
					String userName = loginUser.getUserName();
					String nowTime = TimeTool.getNowTime();
					String content = "用户：" + userName + "，于" + nowTime + " 删除订单：" + o.getId() + "！";
					PublicClass.addLog(userName, loginUser.getLoginName(), "订单管理", 2, content, logServiceImpl);
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return null;
	}

	/**
	 * 跳转到修改页面
	 *
	 * @return type
	 */

	public String toUpdate() {
		try {
			User loginUser = (User) getSession().getAttribute("loginUser");
			if (loginUser != null && StringUtils.isNotBlank(id)) {
				order = orderServiceImpl.getOrderById(id);
				if (order != null && type.equals("update")) {
					return "update";
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		}
		return null;
	}

	/**
	 * 保存订单
	 *
	 * @return 成功标识
	 */
	public String saveOrder() {
		PrintWriter out = null;
		try {
			out = this.getResponse().getWriter();
			User loginUser = (User) getSession().getAttribute("loginUser");
			if (loginUser != null && order != null) {
				if (StringUtils.isNotBlank(type) && type.equals("add")) {// 新增
					order.setId(BaseTool.getPK());
					String userName = loginUser.getUserName();					
					if (StringUtils.isNotBlank(userName)) {
						order.setCreateUserId(loginUser.getId());
						order.setCreateUserName(userName);
					}
					String comCode = loginUser.getComCode();
					if (StringUtils.isNotBlank(comCode)) {
						order.setComCode(comCode);
					}
					orderServiceImpl.saveOrder(order);
					out.print("success");
					// 添加系统日志
					String nowTime = TimeTool.getNowTime();
					String content = "用户：" + userName + "，于" + nowTime + " 添加订单：" + order.getId() + "！";
					PublicClass.addLog(userName, loginUser.getLoginName(), "订单管理", 2, content, logServiceImpl);
				} else if (StringUtils.isNotBlank(type) && type.equals("update")) {// 修改
					Order oldorder = orderServiceImpl.getOrderById(order.getId());
					if (oldorder != null) {
						oldorder.setCreateUserId(id);
						oldorder.setCustomerId(oldorder.getCustomerId());
						String userName = loginUser.getUserName();
						if (StringUtils.isNotBlank(userName)) {
							oldorder.setUpdateUserId(loginUser.getId());
							oldorder.setUpdateUserName(userName);
						}
						orderServiceImpl.updateOrder(oldorder);
						out.print("success");
						// 添加系统日志
						String nowTime = TimeTool.getNowTime();
						String content = "用户：" + userName + "，于" + nowTime + " 修改订单：" + oldorder.getId() + "！";
						PublicClass.addLog(userName, loginUser.getLoginName(), "订单管理", 2, content, logServiceImpl);
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return null;
		} finally {
			if (out != null) {
				out.close();
			}
		}
		return null;
	}
	/**
     * 添加订单表对应的订单信息
     *
     * @param i          		      编号Id
     * @param id      			      订单编号 
     * @param customerName 		      客户名称
     * @param customerAddress     客户地址
     * @param deliverTime         交付日期
     * @param chargeName	                  销售经理
     */
    private boolean addOrder(String i, String id, String customerName, String customerAddress, String chargeName, Customer loginUser, DataEntity pro ) {
        boolean addOrder = false;
        try {
            if (StringUtils.isNotBlank(i) && StringUtils.isNotBlank(id) && StringUtils.isNotBlank(customerName) && StringUtils.isNotBlank(customerAddress)&& StringUtils.isNotBlank(chargeName)) {
            	Order o = orderServiceImpl.getOrderById(id);
                if (o != null) {
                    for (int i1 = 0; i1 < iDisplayLength; i1++) {
                        Order ord = new Order();
                        ord.setId(BaseTool.getPK());
                        ord.setCreateUserName(customerName);
                        String productName = "";
                        ord.setCreateUserName(customerName);
                        String userName = loginUser.getUserName();
                        if (StringUtils.isNotBlank(userName)) {
                            pro.setCreateUserName(userName);
                        }
                        ord.setCreateUserId(loginUser.getId());
                        ord.setComCode(loginUser.getComCode());
                        orderServiceImpl.saveOrder(ord);
                        addOrder = true;
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return addOrder;

    }
}